package com.dcloud.manage.dblib.service.impl;

import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dcloud.core.innerDBOperate.InnerDBOperateService;
import com.dcloud.manage.dblib.entity.DatalibLogicAct;
import com.dcloud.manage.dblib.entity.DatalibLogicTable;
import com.dcloud.manage.dblib.entity.DatalibLogicTableExt;
import com.dcloud.manage.dblib.entity.request.*;
import com.dcloud.manage.dblib.entity.vo.DatalibLogicActVO;
import com.dcloud.manage.dblib.entity.vo.DatalibLogicTableVO;
import com.dcloud.manage.dblib.entity.vo.DatalibTableExtVO;
import com.dcloud.manage.dblib.enumutil.DblibEnum;
import com.dcloud.manage.dblib.enumutil.DblibReturnEnum;
import com.dcloud.manage.dblib.mapper.DatalibLogicActMapper;
import com.dcloud.manage.dblib.mapper.DatalibLogicTableExtMapper;
import com.dcloud.manage.dblib.mapper.DatalibLogicTableMapper;
import com.dcloud.manage.dblib.service.IDatalibLogicTableService;
import com.dcloud.utils.SpringBeanUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: datalib_logic_table
 * @Author: jeecg-boot
 * @Date:   2024-03-11
 * @Version: V1.0
 */
@Service
public class DatalibLogicTableServiceImpl extends ServiceImpl<DatalibLogicTableMapper, DatalibLogicTable> implements IDatalibLogicTableService {

    @Autowired
    private DatalibLogicTableMapper datalibLogicTableMapper;

    @Autowired
    private DatalibLogicActMapper datalibLogicActMapper;

    @Autowired
    private DatalibLogicTableExtMapper datalibLogicTableExtMapper;

    @Autowired
    private InnerDBOperateService innerDBOperateService;

    @Override
    public IPage<DatalibLogicTableVO> selectPage(Page<DatalibLogicTableVO> page, DatalibLogicTablePageReq datalibLogicTablePageReq) {
        IPage<DatalibLogicTableVO> pageDate = datalibLogicTableMapper.selectPageListInfo(page,datalibLogicTablePageReq);
        return pageDate;
    }

    @Override
    public Integer saveReturnId(DatalibLogicTable datalibLogicTable) {
        datalibLogicTable.setStatus(DblibEnum.DBLIB_STATUS_DRAFT.getCode());
        datalibLogicTable.setCreateTime(new Date());
        datalibLogicTableMapper.insert(datalibLogicTable);
        return datalibLogicTable.getId();
    }

    /**
     * @Description:根据表id删除逻辑表，以及表字段信息
     * @param id 表id
     * @return: void
     * @Author: shijf
     * @Date 2024/3/17 17:03
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removeByIdAFieldMap(String id) {
        datalibLogicTableMapper.deleteById(id);
        datalibLogicActMapper.delete(new LambdaQueryWrapper<DatalibLogicAct>().eq(DatalibLogicAct::getDatalibTableId,id));
    }

    /**
     * @Description:
     * @param tableId 表id
     * @return: DatalibTableExtVO
     * @Author: shijf
     * @Date 2024/3/27 16:31
     */
    @Override
    public DatalibTableExtVO queryExtInfoById(Integer tableId) {

        //判断表id所在的资源表是否存在
        DatalibLogicTable datalibLogicTable = datalibLogicTableMapper.selectById(tableId);
        if(datalibLogicTable == null){
            throw new RuntimeException(DblibReturnEnum.ERROR_NOTABLE.getValue());
        }

        //表存在，查询扩展信息
        DatalibLogicTableExt datalibLogicTableExt = datalibLogicTableExtMapper.selectOne(new LambdaQueryWrapper<DatalibLogicTableExt>().eq(DatalibLogicTableExt::getTableId, tableId));
        if(datalibLogicTableExt == null){
            datalibLogicTableExt = new DatalibLogicTableExt();
            datalibLogicTableExt.setTableId(tableId);

            //查询表映射字段
            String keys = datalibLogicActMapper.selectGroupKeysByTableId(tableId);
            datalibLogicTableExt.setKeyCodes(keys);

            datalibLogicTableExt.setCreateTime(new Date());
            datalibLogicTableExtMapper.insert(datalibLogicTableExt);

            return SpringBeanUtil.copyProperties(datalibLogicTableExt, DatalibTableExtVO.class);

        }else{

            DatalibTableExtVO datalibTableExtVO = SpringBeanUtil.copyProperties(datalibLogicTableExt, DatalibTableExtVO.class);
            datalibTableExtVO.setTableShowName(datalibLogicTable.getTableCode()+"("+datalibLogicTable.getTableName()+")");
            return datalibTableExtVO;
        }
    }

    @Override
    public void updateExtInfo(UpdateTableExtReq updateTableExtReq) {
        datalibLogicTableExtMapper.updateById(updateTableExtReq);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void publish(DatalibTablePublishReq datalibTablePublishReq) {
        Integer tableId = datalibTablePublishReq.getTableId();

        //资产表信息
        DatalibLogicTable datalibLogicTable = datalibLogicTableMapper.selectById(tableId);

        //数据字段信息
        List<DatalibLogicActVO> listByTableId = datalibLogicActMapper.getListByTableId(String.valueOf(tableId));

        //扩展信息 分区字段，key字段等
        DatalibTableExtVO datalibTableExtVO = queryExtInfoById(tableId);

        //创建表
        innerDBOperateService.createTable(datalibLogicTable, listByTableId, datalibTableExtVO);

        //修改资产表信息，将发布状态改为已发布
        datalibLogicTable.setStatus(DblibEnum.DBLIB_STATUS_UNPUBLISHED.getCode());
        datalibLogicTableMapper.updateById(datalibLogicTable);

    }


    /**
     * @describle 数据资源即席查询
     * @param datalibJXCXReq
     * return Map<String,Object>
     * @author shijf
     * @date 2024/9/19 14:37
     * @description
     */
    @Override
    public Map<String, Object> jxcx(DatalibJXCXReq datalibJXCXReq) {

        Integer tableId = datalibJXCXReq.getTableId();

        //资产表信息
        DatalibLogicTable datalibLogicTable = datalibLogicTableMapper.selectById(tableId);

        List<Map<String, Object>> jxcx = innerDBOperateService.jxcx(datalibLogicTable, datalibJXCXReq.getSql(), datalibJXCXReq.getPageNo(), datalibJXCXReq.getPageSize());

        //处理通用表格标题
        if(jxcx.size() == 0){
            return null;
        }

        //获取第一条数据的KEY作为表头
        Map<String, Object> firstRow = jxcx.get(0);
        List<String> keys = firstRow.keySet().stream().collect(Collectors.toList());

        return MapUtil.builder(new LinkedHashMap<String,Object>())
                .put("data", jxcx)
                .put("keys", keys)
                .build();
    }

    /**
     * @param datalibInnerTableInfoReq return Map<String,Object>
     * @describle 数据资源表DDL信息
     * @author shijf
     * @date 2024/9/19 14:36
     * @description
     */
    @Override
    public String innerTableInfo(DatalibInnerTableInfoReq datalibInnerTableInfoReq) {
        Integer tableId = datalibInnerTableInfoReq.getTableId();

        //资产表信息
        DatalibLogicTable datalibLogicTable = datalibLogicTableMapper.selectById(tableId);

        //资产表信息
        String sql = innerDBOperateService.ddlInfo(datalibLogicTable.getTableCode(),datalibLogicTable.getTableSourceId());
        return sql;
    }
}
